package ar.edu.unq.tpi.uis.tepe3.wicket.pages;

import org.apache.wicket.Component;
import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.PageLink;
import org.apache.wicket.model.CompoundPropertyModel;

import ar.edu.unq.tpi.uis.tepe3.wicket.components.UserListView;
import ar.edu.unq.tpi.uis.tepe3.wicket.model.UserList;


public class UserPage extends LayoutPage {
	
	private Component resultSection;
	
	public UserPage(PageParameters parameters) {
		super(new CompoundPropertyModel(new UserList()));
		this.setActiveClass("user");
		this.createForm();
		this.add(new PageLink("newUser", NewUserPage.class));
	}
	
	protected void createForm(){
		Form form = new Form("userSearchForm", this.getModel());
		this.add(form);
		this.addSearchFields(form);
		this.addButtons(form);
		this.resultSection = this.createList();
		form.add(this.resultSection);
	}
	
	protected WebMarkupContainer createList() {
		WebMarkupContainer panel = new WebMarkupContainer("resultSection");
		panel.setOutputMarkupId(true);
		panel.add(new UserListView("result", panel, this.getModelObject()));
		return panel;
	}

	protected void addSearchFields(Form form) {
		form.add(new TextField("name"));
	}

	protected void addButtons(Form form) {
		form.add(new AjaxButton("search") {
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				((UserList) form.getModelObject()).search();
				target.addComponent(getResultSection());
			}
		});
		form.add(new AjaxButton("clean") {
			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				((UserList) form.getModelObject()).clean();
				((UserList) form.getModelObject()).loadAllUsers();
				target.addComponent(getResultSection());
			}
		});
	}
	
	public Component getResultSection(){
		return this.resultSection;
	}
}
